#include "base/logging.h"
#include "base/config_reader.h"

#include "fcgi_service/fcgi_service.h"
#include "down_stream_request.h"
#include "upload_stream_request.h"
#include "flash_upload_stream_request.h"

using namespace fcgi;

namespace imserver {
namespace fcgi {
/*
std::map<std::string, std::string> gFCTypes;

void initTypes() {
#define ADD_CONTENT_TYPE(x, t)\
  gFCTypes.insert(std::make_pair(x, t));\
  std::cout << x << " | " << t << std::endl;
  ADD_CONTENT_TYPE(".jpg", "image/jpeg")
  ADD_CONTENT_TYPE(".jpeg", "image/jpeg")
  ADD_CONTENT_TYPE(".png", "image/png")
  ADD_CONTENT_TYPE(".gif", "image/gif")
  ADD_CONTENT_TYPE(".zip", "application/octet-stream")
  ADD_CONTENT_TYPE(".rar", "application/octet-stream")
  ADD_CONTENT_TYPE(".txt", "text/plain")
  ADD_CONTENT_TYPE(".doc", "application/msword")
  ADD_CONTENT_TYPE(".docx", "application/msword")
#undef ADD_CONTENT_TYPE
}
*/
std::string g_file_exts;

class FileTransRequestFactory : public RequestFactory {
public:
  virtual RequestPtr Create(FCGX_Request * r) {
    LOG_DEBUG("[FileTransRequestFactory::Create] called.");
    char * path = FCGX_GetParam("SCRIPT_NAME", r->envp);
    RequestPtr req;
    if (path) {
      if (strcmp(path, "/ft/upstream") == 0) {
        req = RequestPtr(new FileTransUpstreamRequest(r));
      } else if (strcmp(path, "/ft/upstreamajax") == 0) {
        req = RequestPtr(new FileTransFlashUpstreamRequest(r));
      } else if (strcmp(path, "/ft/d") == 0) {
        req = RequestPtr(new FileTransDownstreamRequest(r));
      }
    }
    return req;
  }
};

}
}

int main(int argc, char **argv) {
  char * conf_file = "../conf/file_transfer_service.conf";
  char opt;
  while ((opt = getopt(argc, argv, "c:")) != -1) {
    switch (opt) {
    case 'c':
      conf_file = optarg;
      break;
    default:
      std::cerr << "Unknown option " << optopt << std::endl;
      return 1;
    }
  }

  ConfigReader cfg(conf_file);
  if (!cfg) {
    std::cerr << "Config file " << conf_file << " read error!" << std::endl;
    return 1;
  }

  //::imserver::fcgi::initTypes();
  ::imserver::fcgi::g_file_exts = cfg.Get("rename_list", "list");
  LOG_INIT(cfg.Get("log4cplus", "file"), cfg.Get("log4cplus", "level"));
  // FcgiServer * fcgi_server = new FcgiServer("127.0.0.1:19000", 128);

  std::string bind_addr = cfg.Get("file_transfer_service", "bind");

  LOG_INFO("listens on port " << bind_addr);

  FcgiServer * fcgi_server = new FcgiServer(bind_addr, 128);
  fcgi_server->RegisterRequestFactory(RequestFactoryPtr(new imserver::fcgi::FileTransRequestFactory()));
  fcgi_server->Start(true); // 本线程也处理 fcgi 请求，不退出
  return 0;
}

